package com.midongtec.mduisdkdemo;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hrs on 2018/3/19.
 */

public class AppUtils {

    private static final String TAG = "AppUtils";

    private static long lastClickTime;
    private static String sLastTopApp = "";
    private static String sLastTopAppActivity = "";

    /**
     * 获取安装列表app包名
     *
     * @param context
     * @return
     */
    public final static synchronized ArrayList<String> getInstalledAppsPackage(Context context) {
        ArrayList<String> apps = new ArrayList<String>();
        if (context.getPackageManager() != null) {
            List<PackageInfo> packages = getInstalledPackages(context, 0);
            for (int i = 0; i < packages.size(); i++) {
                PackageInfo packageInfo = packages.get(i);
                //只有非系统应用才上报
                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    String appName = packageInfo.packageName;
                    apps.add(appName);
                }
            }
            return apps;
        }
        return null;
    }

    public static synchronized List<String> getInstallAppList2(Context context) {
        List<PackageInfo> pinfo = getInstalledPackages(context, 0);
        StringBuilder builder = new StringBuilder();
        StringBuilder builderAppName = new StringBuilder();
        StringBuilder lastUpdateTime = new StringBuilder();
        StringBuilder versionCodes = new StringBuilder();
        PackageManager packageManager = context.getPackageManager();
        if (pinfo != null) {
            int size = pinfo.size();
            for (int i = 0; i < size; i++) {
                builder.append(pinfo.get(i).packageName);
                builderAppName.append(pinfo.get(i).applicationInfo.loadLabel(packageManager).toString());
                lastUpdateTime.append(pinfo.get(i).lastUpdateTime);
                versionCodes.append(pinfo.get(i).versionCode);
                if (i < size - 1) {
                    builder.append(",");
                    builderAppName.append(",");
                    lastUpdateTime.append(",");
                    versionCodes.append(",");
                }
            }
        }
        List<String> name = new ArrayList<>();
        name.add(builder.toString());
        name.add(builderAppName.toString());
        name.add(lastUpdateTime.toString());
        name.add(versionCodes.toString());
        return name;
    }

    /**
     * 获取App的名称
     */
    public static String getAppName(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //获取应用 信息
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            //获取albelRes
            int labelRes = applicationInfo.labelRes;
            //返回App的名称
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<PackageInfo> getInstalledPackages(Context context, int flags) {
        final PackageManager pm = context.getPackageManager();
        try {
            return pm.getInstalledPackages(flags);
        } catch (Exception ignored) {
            //we don't care why it didn't succeed. We'll do it using an alternative way instead
        }
        //抛异常后,备选方案通过adb命令去获取已安装的应用列表(比较耗时,所以在异常捕获的前提下优先使用上面的系统api)
        Process process;
        List<PackageInfo> result = new ArrayList<>();
        BufferedReader bufferedReader = null;
        try {
            process = Runtime.getRuntime().exec("pm list packages");
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                final String packageName = line.substring(line.indexOf(':') + 1);
                final PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
                result.add(packageInfo);
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null)
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return result;
    }

    public static void startApp(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean isApkValid(String apkPath, Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                return true;
            } else {
                Log.e("hyw", "isApkValid Exception:" +false);
                return false;
            }
        } catch (Exception e) {
            Log.e("hyw", "isApkValid Exception:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    // 将Unix时间戳转变为日期，如调用TimeStampToDate("1252639886", "yyyy-MM-dd
    // HH:mm:ss")返回值：2009-11-09 11:31:26

    public static boolean isAppInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info == null) {
                return false;
            } else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 判断当前设备中有没有“有权查看使用权限的应用”这个选项
     *
     * @param context
     * @return
     */
    public static boolean hasOption(Context context) {
        PackageManager packageManager = context.getApplicationContext()
                .getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 判断调用该设备中“有权查看使用权限的应用”这个选项的APP有没有打开
     */
    public static boolean isSwitchOpen(Context context) {
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            usageStatsManager = (UsageStatsManager) context.getApplicationContext()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
        }
        if (usageStatsManager == null)
            return false;
        List<UsageStats> queryUsageStats = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            queryUsageStats = usageStatsManager.queryUsageStats(
                    UsageStatsManager.INTERVAL_BEST, 0, ts);
        }
        if (queryUsageStats != null && queryUsageStats.size() > 0)
            return true;
        else return false;
    }

    public static String TimeStamp2Date(Long timestamp, String formats) {
        String date = "";
        try {
            date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));

        } catch (NumberFormatException e) {

        }
        return date;
    }

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 800) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public synchronized static boolean isFastClick2() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 800) {
            lastClickTime = time;
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static String[] getTopAppInfo(Context context) {
        String[] info = new String[]{sLastTopApp, sLastTopAppActivity};
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
            if (null != appTasks && !appTasks.isEmpty()) {
                info[0] = appTasks.get(0).topActivity.getPackageName();
                info[1] = appTasks.get(0).topActivity.getClassName();
                return info;
            }
        } else {
            long endTime = System.currentTimeMillis();
            long beginTime = endTime - 1 * 60 * 1000;
            UsageStatsManager manager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            String result = "";
            String resultActivity = "";
            UsageEvents.Event event = new UsageEvents.Event();
            UsageEvents usageEvents = manager.queryEvents(beginTime, endTime);
            while (usageEvents.hasNextEvent()) {
                usageEvents.getNextEvent(event);
                if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    result = event.getPackageName();
                    resultActivity = event.getClassName();
                }
            }
            if (!TextUtils.isEmpty(result)) {
                sLastTopApp = result;
            }
            if (!TextUtils.isEmpty(resultActivity)) {
                sLastTopAppActivity = resultActivity;
            }
            info[0] = sLastTopApp;
            info[1] = sLastTopAppActivity;
            return info;
        }
        return info;
    }

    public static String getLauncherTopApp(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appTasks = activityManager.getRunningTasks(1);
            if (null != appTasks && !appTasks.isEmpty()) {
                return appTasks.get(0).topActivity.getPackageName();
            }
        } else {
            long endTime = System.currentTimeMillis();
            long beginTime = endTime - 1 * 60 * 1000;
            UsageStatsManager manager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            String result = "";
            UsageEvents.Event event = new UsageEvents.Event();
            UsageEvents usageEvents = manager.queryEvents(beginTime, endTime);
            while (usageEvents.hasNextEvent()) {
                usageEvents.getNextEvent(event);
                if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    result = event.getPackageName();
                }
            }
            if (!TextUtils.isEmpty(result)) {
                sLastTopApp = result;
                return result;
            } else {
                return sLastTopApp;
            }
        }
        return "";
    }


    /**
     * 打开应用的指定页面
     *
     * @param context
     * @param packageName
     * @param activityFullName
     * @return
     */
    public static boolean openAppTargetPage(Context context, String packageName, String activityFullName) {
        try {
            Intent intent = new Intent();
            intent.setClassName(packageName, activityFullName);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getSHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void openAppUrlWithBrowser(Activity activity, String url) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
        }
    }

    /**
     * 过滤非数字
     *
     * @param str
     * @return
     */
    public static String getNumeric(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        String regEx = "[^0-9|^.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String getNumericInt(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        String regEx = "[^0-9|^.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String ss = m.replaceAll("").trim();
        if (ss.contains(".")) {
            ss = ss.split("\\.")[0];
        }
        return ss;
    }

    public static boolean openDeepLink(Context ctx, String url) {
        try {
            Intent intent1 = new Intent();
            intent1.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent1.setData(uri);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ctx.startActivity(intent1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断 悬浮窗口权限是否打开
     *
     * @param context
     * @return true 允许 false禁止
     */
    public static boolean getAppOps(Context context) {
        return false;
    }

    public static void openAppByMarket(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) {
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定应用的版本号
     * @param context
     * @param pkg  包名
     * @return
     */
    public static long getAppVersionCode(Context context, String pkg) {
        long versionCode = 0;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                versionCode = context.getPackageManager().getPackageInfo(pkg, 0).getLongVersionCode();
            } else {
                versionCode = context.getPackageManager().getPackageInfo(pkg, 0).versionCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }



}
